<template>
  <div class="table-container">
    <byui-query-form>
      <byui-query-form-left-panel>
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleAdd"
          v-if="checkPermission(['admin'])"
          >添加</el-button
        >
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete"
          >删除</el-button
        >
      </byui-query-form-left-panel>
    </byui-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      @selection-change="setSelectRows"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="ID" width="95" prop="id"></el-table-column>
      <el-table-column label="账号" prop="name"></el-table-column>
      <el-table-column label="媒体数量" prop="channel" width="100">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            placement="right"
            v-if="Object.keys(scope.row.channel).length > 0"
          >
            <div slot="content">
              <div
                v-for="(item, index) in scope.row.channel"
                :key="index"
                style="line-height: 15px;"
              >
                {{ item.name }}--{{ item.id }}
              </div>
            </div>
            <div>{{ Object.keys(scope.row.channel).length }}</div>
          </el-tooltip>
          <div v-else>0</div>
        </template>
      </el-table-column>
      <!--el-table-column label="PID" prop="pid"></el-table-column>
      <el-table-column label="AppKey" prop="appkey"></el-table-column>
      <el-table-column label="AppSecret" prop="appsecret"></el-table-column-->
      <el-table-column
        label="添加时间"
        prop="addtime"
        :formatter="formatDate"
      ></el-table-column>
      <el-table-column label="授权时间" prop="authtime"></el-table-column>
      <el-table-column label="操作" width="380">
        <template slot-scope="scope">
          <el-button type="success" size="mini" @click="auth(scope.row)"
            >授权</el-button
          >
          <!--el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button-->
          <el-button type="primary" size="mini" @click="addChannel(scope.row)"
            >添加媒体</el-button
          >
          <el-button type="danger" size="mini" @click="delChannel(scope.row)"
            >删除媒体</el-button
          >
          <el-button type="warning" size="mini" @click="tableDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
    <edit ref="edit" @msgEvent="saveUnion"></edit>
    <el-dialog
      title="添加媒体"
      :visible.sync="addChannelShow"
      width="500px"
      center
      :close-on-click-modal="closeModel"
    >
      <el-form ref="channelForm" :model="channelForm" label-width="150px">
        <el-form-item
          label="媒体名称"
          prop="name"
          :rules="[
            { required: true, message: '请输入媒体名称', trigger: 'blur' },
          ]"
        >
          <el-input
            v-model="channelForm.name"
            placeholder="自己备注方便以后查看"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="默认PID"
          prop="pid"
          :rules="[
            {
              required: true,
              message: '请输入默认PID，一般为管理员使用',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="channelForm.pid"
            placeholder="请输入默认PID，一般为管理员使用"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="媒体ID"
          prop="id"
          :rules="[{ required: true, message: '请输入媒体', trigger: 'blur' }]"
        >
          <el-input
            v-model="channelForm.id"
            placeholder="例:mm_1221_2222_3333,中间的2222就是媒体ID"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="媒体对应Appkey"
          prop="appkey"
          :rules="[
            {
              required: true,
              message: '请输入媒体对应Appkey',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="channelForm.appkey"
            placeholder="必须是对应上面媒体,否则淘礼金无法生成"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="媒体对应Appsecret"
          prop="appsecret"
          :rules="[
            {
              required: true,
              message: '请输入媒体对应Appsecret',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="channelForm.appsecret"
            placeholder="必须是对应上面媒体,否则淘礼金无法生成"
          ></el-input>
        </el-form-item>
        <el-form-item
          ><el-button type="primary" @click="addChannel()"
            >提交</el-button
          ></el-form-item
        >
      </el-form>
    </el-dialog>
    <el-dialog
      title="删除媒体"
      :visible.sync="delChannelShow"
      width="360px"
      center
      :close-on-click-modal="closeModel"
    >
      <el-form ref="delChannelForm" :model="channelForm" label-width="70px">
        <el-form-item
          label="媒体ID"
          prop="id"
          :rules="[
            { required: true, message: '请需要删除媒体', trigger: 'change' },
          ]"
        >
          <el-select v-model="channelForm.id" placeholder="请选择媒体ID">
            <el-option
              v-for="(item, index) in channelList"
              :key="index"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="delChannel()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import checkPermission from "@/utils/permission";
import {
  listUnionTaobao,
  listUnionChannel,
  delUnionTaobao,
  delChannel,
  addUnionTaobao,
  addUnionTaobaoSession,
  addChannel,
} from "@/api/index";
import Edit from "./components/edit";

export default {
  name: "Table",
  components: {
    Edit,
  },
  filters: {},
  data() {
    return {
      closeModel: false,
      addChannelShow: false,
      delChannelShow: false,
      channelList: [],
      channelForm: { id: 0 },
      list: [],
      listLoading: true,
      layout: "total, sizes, prev, pager, next, jumper",
      total: 0,
      background: true,
      selectRows: "",
      elementLoadingText: "正在加载...",
      queryForm: {
        pageNo: 1,
        pageSize: 20,
      },
    };
  },
  created() {
    this.fetchData();
  },
  beforeDestroy() {},
  mounted() {},
  methods: {
    auth(row) {
      window.open(
        "https://oauth.taobao.com/authorize?response_type=token&client_id=27754179"
      );
      this.$prompt("请输入【" + row.name + "】对应的Session", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /[a-z0-9]{55,}/,
        inputErrorMessage: "Session输入错误,请注意是否有空格/换行",
        closeOnClickModal: false,
      }).then(({ value }) => {
        addUnionTaobaoSession({ session: value, id: row.id }).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "授权成功",
            });
            this.fetchData();
          }
        });
      });
    },
    setSelectRows(val) {
      this.selectRows = val;
    },
    addChannel(e) {
      if (e) {
        this.channelForm = {
          unionId: e.id,
          id: "",
          name: "",
          appkey: "",
          appsecret: "",
          pid: "",
        };
        this.addChannelShow = true;
      } else {
        this.$refs["channelForm"].validate((valid) => {
          if (valid) {
            if (isNaN(Number(this.channelForm.id))) {
              return this.$baseMessage(
                "请输入正确的媒体ID，例：mm_111_222_333，222则为媒体ID",
                "error"
              );
            }
            if (isNaN(Number(this.channelForm.appkey))) {
              return this.$baseMessage("请输入正确的Appkey", "error");
            }
            addChannel(this.channelForm).then((res) => {
              this.$baseMessage(res.msg, "success");
              this.addChannelShow = false;
              this.fetchData();
            });
          } else {
            return false;
          }
        });
      }
    },
    delChannel(e) {
      if (e) {
        this.channelForm = { unionId: e.id, id: "" };
        listUnionChannel(this.channelForm).then((res) => {
          this.channelList = res.data.channel;
          this.delChannelShow = true;
        });
      } else {
        this.$refs["delChannelForm"].validate((valid) => {
          if (valid) {
            delChannel(this.channelForm).then((res) => {
              this.$baseMessage(res.msg, "success");
              this.delChannelShow = false;
              this.fetchData();
            });
          } else {
            return false;
          }
        });
      }
    },
    handleAdd() {
      this.$refs["edit"].showEdit();
    },
    handleDelete() {
      if (this.selectRows.length === 0) {
        return this.$baseMessage("请至少选择一项", "error");
      }
      const ids = this.selectRows.map((item) => item.id).join();
      this.$baseConfirm("你确定要删除选中项吗", null, () => {
        delUnionTaobao({ id: ids }).then((res) => {
          if (res.code && res.code === 200) {
            this.fetchData();
            this.$baseMessage(res.msg, "success");
          }
        });
      });
    },
    tableDelete(row) {
      this.$baseConfirm("你确定要删除" + row.name + "吗", null, () => {
        delUnionTaobao({ id: row.id }).then((res) => {
          if (res.code && res.code === 200) {
            this.$baseMessage(res.msg, "success");
            this.fetchData();
          }
        });
      });
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val;
      this.fetchData();
    },
    handleQuery() {
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      listUnionTaobao(this.queryForm).then((res) => {
        this.list = res.data;
        this.total = res.totalCount;
        setTimeout(() => {
          this.listLoading = false;
        }, 500);
      });
    },
    formatDate(row, column) {
      let date = new Date(parseInt(row.addtime) * 1000);
      let Y = date.getFullYear() + "-";
      let M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1) + "-"
          : date.getMonth() + 1 + "-";
      let D =
        date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
      let h =
        date.getHours() < 10
          ? "0" + date.getHours() + ":"
          : date.getHours() + ":";
      let m =
        date.getMinutes() < 10
          ? "0" + date.getMinutes() + ":"
          : date.getMinutes() + ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    saveUnion(e) {
      addUnionTaobao(e).then((res) => {
        if (res.code && res.code === 200) {
          this.$baseMessage(res.msg, "success");
          this.$refs["edit"].close();
          this.fetchData();
        }
      });
    },
    checkPermission,
  },
};
</script>
<style lang="scss" scoped></style>
